<?php

namespace App\Models;

use App\Util\Tool;
use Carbon\Carbon;
use Encore\Admin\Form\Field\Date;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class TargetLog extends Model
{
    protected $table = "c_target_logs";

    public function target()
    {
        return $this->belongsTo('App\Models\Target', 'target_id');
    }

    /****
     * @param $data
     * @return bool
     * 添加备忘录
     */
    public function doSetting($data)
    {
        if (isset($data['id']) && !empty($data['id'])) {
            $redata = $this->getInfo($data['id']);
            $redata->case_id = isset($data['case_id'])?$data['case_id']:"";
            $redata->remark = isset($data['remark'])?$data['remark']: $redata->remark;
            $redata->ins_times = $data['ins_times'];
            $redata->user_id = $data['user_id'];
            $redata->high = $data['high'];
            $redata->low = isset($data['low'])?$data['low']:"";
            $redata->target_id = $data['target_id'];
            $res = $redata->save();
        } else {
            //添加
//            $have = $this->hasTodays($data);
//            if ($have !== true) {
//                return $have;
//            }
            $this->case_id = isset($data['case_id'])?$data['case_id']:"";
            $this->remark = isset($data['remark'])?$data['remark']:"";
            $this->ins_times = $data['ins_times'];
            $this->user_id = $data['user_id'];
            $this->high = $data['high'];
            $this->low = isset($data['low'])?$data['low']:"";
            $this->target_id = $data['target_id'];
            $res = $this->save();
        }
        return $res;
    }

    public function hasTodays($data)
    {
        $res = $this->where([['case_id', '=', $data['case_id']], ['ins_times', '=', $data['ins_times']]])->first();
        if (!empty($res)) {
            return "今日您已经添加指标,不能重复添加!";
        }
        return true;
    }

    /***
     * @param $data
     * @return mixed
     * 获取备忘录信息
     */
    public function getInfo($id)
    {
        return $this->where([['id', '=', $id]])->first();
    }

    /****
     * @param $data
     * 获取备忘录列表
     */
    public function getTargetsLogList($param)
    {
        $where = [];
//        if (isset($param['start']) && !empty($param['start'])) {  //开始时间
//            $where[] = ['ins_times', '>=', $param['start']];
//        }
//        if (isset($param['end']) && !empty($param['end'])) {  //开始时间
//            $where[] = ['ins_times', '<=', $param['end']];
//        }
        if (isset($param['end']) && !empty($param['end']) && isset($param['start']) && !empty($param['start'])) {  //开始时间
            $where[] = [function ($query) use ($param) {
                $query->whereBetween('ins_times', [$param['start'], $param['end']]);
            }];
            $or[] = [function ($query) use ($param) {
                $query->whereBetween('ins_times', [$param['start'], $param['end']]);
            }];
        }
        if (isset($param['user_id']) && !empty($param['user_id'])) {  //用户id
            $where[] = ['user_id', '=', $param['user_id']];
        }
        if (isset($param['case_id']) && !empty($param['case_id'])) {  //case-di
            $where[] = ['case_id', '=', $param['case_id']];
        }
        if (isset($param['target_id']) && !empty($param['target_id'])) {  //target_id
            $where[] = ['target_id', '=', $param['target_id']];
            $or[] = ['target_id', '=', $param['target_id']];
        }
        $or[] = ["case_id", '=', 0];
        $or[] = ["user_id", '=', $param['user_id']];
        $list = $this->with(['target'])->where($where)->orWhere($or)->orderByDesc("ins_times")->orderByDesc("id")->get();
        if (!empty($list)) {
            $list = $list->toArray();
            $list = self::array_group_by($list, 'ins_times');
            return $list;
        }
        return [];
    }

    /**
     * @param $param
     * @return TargetLog[]|array|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     * android使用
     */
    public function getTargetsLogListAndroid($param)
    {
        $where = [];
//        if (isset($param['start']) && !empty($param['start'])) {  //开始时间
//            $where[] = ['ins_times', '>=', $param['start']];
//            $or[] = ['ins_times', '>=', $param['start']];
//        }
        if (isset($param['end']) && !empty($param['end']) && isset($param['start']) && !empty($param['start']) ) {  //开始时间
            $where[] = [function ($query) use ($param) {
                $query->whereBetween('ins_times', [$param['start'], $param['end']]);
            }];
            $or[] = [function ($query) use ($param) {
                $query->whereBetween('ins_times', [$param['start'], $param['end']]);
            }];
        }
        if (isset($param['user_id']) && !empty($param['user_id'])) {  //用户id
            $where[] = ['user_id', '=', $param['user_id']];
        }
        if (isset($param['case_id']) && !empty($param['case_id'])) {  //case-di
            $where[] = ['case_id', '=', $param['case_id']];
        }
        if (isset($param['target_id']) && !empty($param['target_id'])) {  //target_id
            $where[] = ['target_id', '=', $param['target_id']];
            $or[] = ['target_id', '=', $param['target_id']];
        }
//        $or[] = ["case_id",'=',0];
//        $or[] = ["user_id",'=',$param['user_id']];
//        $list = $this->with(['target'])->where($where)->orWhere($or)->orderByDesc("ins_times")->orderByDesc("id")->get();
        $list = $this->with(['target'])->where($where)->orderByDesc("ins_times")->orderByDesc("id")->get();
        if (!empty($list)) {
            $list = $list->toArray();
//            $list = self::array_group_by($list, 'ins_times');
            return $list;
        }
        return [];
    }


    /***
     * @param $list
     * @return array
     * 分组排序
     */
    public static function array_group_by($list)
    {
        $newArray = array();
        foreach ($list as $v) {
            $newArray[$v['ins_times']][] = $v;
        }
        return $newArray;
    }

    /***
     * @param $data
     * @return int
     * 删除备忘录
     */
    public function delTargetsLog($data)
    {
        return $this::destroy($data['id']);
    }


    public function getTargetsStatisticalAndroid($data)
    {
//        $where[] = ['user_id', '=', $data['user_id']];
//        $where[] = ['target_id', '=', $data['target_id']];
//        $currentDate = Carbon::now();
//        $weekStart = $currentDate->subMonth();
//        $weekEnd = $currentDate->now();
//        $carbonDate1 = Carbon::createFromFormat('Y-m-d', $weekStart->toDateString());
//        $carbonDate2 = Carbon::createFromFormat('Y-m-d', $weekEnd->toDateString());
//        // 计算两个日期之间的差异
//        $daysInMonth = $carbonDate1->diffInDays($carbonDate2);
//        $res = DB::select('select * from c_target_logs as a right join (select  max(id) as bid from c_target_logs
//              where ins_times BETWEEN :weekStart AND :weekEnd and target_id= :target_id and user_id = :user_id
//              group by ins_times) as b on a.id=b.bid  order by a.ins_times desc',
//            ['weekStart' => $weekStart, 'weekEnd' => $weekEnd, 'target_id' => $data['target_id'], 'user_id' => $data['user_id']]);
        $res = (new TargetLog())->where([['target_id','=', $data['target_id']],['user_id','=', $data['user_id']],['case_id','=', $data['case_id']]])->orderByDesc("ins_times")->orderByDesc("id")->limit(7)->get();;
        $result = [];
        $result['list'] = [];
        $result['target_name'] = (new Target())->where([['id','=',$data['target_id']]])->value("name");
        if(!empty($res)) {
            $result['list'] = $res;
        }
//        $kk = 0;
//        for ($i = 1; $i <= $daysInMonth; $i++) {
//            $d =  $this->getDayBeforeDays($i-1);
////            $result['day'][$i - 1] = str_replace('-','/',substr($d,2));
////            $result['high'][$i - 1] = 0;
////            $result['low'][$i - 1] = 0;
//            if(empty($res)){
//                continue;
//            }

            foreach ($res as $k => $v) {
//                dd($v->ins_times);
//                if ($d == $v->ins_times) {
                    $result['day'][$k] =date("m-d",strtotime($v->ins_times)); //str_replace('-','/',substr($d,2));
                    $result['high'][$k] = $v->high;
                    $result['low'][$k] = $v->low;
//                    $kk++;
//                }
//                else{
//                    $result['day'][$i - 1] = str_replace('-','/',substr($d,2));
//                    $result['high'][$i - 1] = 0;
//                    $result['low'][$i - 1] = 0;
//                }
            }
//        }
        return $result;
    }










    /**
     * @param $data
     * 获取统计图
     *
     * // 获取当前日期
    $today = Carbon::now();

    // 向前推1个月
    $oneMonthAgo = $today->subMonth();
     */
    public function getTargetsStatistical($data)
    {
//        $where[] = ['user_id', '=', $data['user_id']];
////        $where[] = ['case_id', '=', $data['case_id']];
//        $where[] = ['target_id', '=', $data['target_id']];
//        $currentDate = Carbon::now();
//        $weekStart = $currentDate->subMonth();
//        $weekEnd = $currentDate->now();
//        $carbonDate1 = Carbon::createFromFormat('Y-m-d', $weekStart->toDateString());
//        $carbonDate2 = Carbon::createFromFormat('Y-m-d', $weekEnd->toDateString());
//        // 计算两个日期之间的差异
//        $daysInMonth = $carbonDate1->diffInDays($carbonDate2);
        // 获取当前月份的最后一天
//        $lastDayOfMonth = $currentDate->copy()->endOfMonth();
//        // 获取当月有多少天
//        $daysInMonth = $lastDayOfMonth->day;
//        $weekStart = Carbon::now()->startOfMonth();
//        $weekEnd = Carbon::now()->endOfMonth();
    //        $res = DB::select('select * from c_target_logs as a right join (select  max(id) as bid from c_target_logs
    //              where ins_times BETWEEN :weekStart AND :weekEnd and target_id= :target_id and user_id = :user_id
    //              group by ins_times) as b on a.id=b.bid  order by a.ins_times desc',
    //             ['weekStart' => $weekStart, 'weekEnd' => $weekEnd, 'target_id' => $data['target_id'], 'user_id' => $data['user_id']]);
//        $res = $this::select(DB::raw('max(id) as sort_id'), "c_target_logs.*")
//            ->whereBetween('ins_times', [$weekStart, $weekEnd])
//            ->where($where)
//            ->groupBy("ins_times")
//            ->orderBy("sort_id", "desc")
//            ->get();
        $res = (new TargetLog())->where([['target_id','=', $data['target_id']],['user_id','=', $data['user_id']],['case_id','=',$data['case_id']]])->orderByDesc("ins_times")->orderByDesc("id")->limit(7)->get();;
        $result = [];
        $result['list'] = [];
        $result['target_name'] = (new Target())->where([['id','=',$data['target_id']]])->value("name");
        if(!empty($res)) {
            $result['list'] = $res;
        }
//        $days = date("Y-m", time());
//        for ($i = 1; $i <= $daysInMonth; $i++) {
//           $d =  $this->getDayBeforeDays($i-1);
//            if ($i < 10) {
//                $ii = '0' . $i;
//            }else{
//                $ii = $i;
//            }
//            $result['day'][$i - 1] = str_replace('-','/',substr($d,2));
//            $result['high'][$i - 1] = 0;
//            $result['low'][$i - 1] = 0;
//            if(empty($res)){
//                continue;
//            }
            foreach ($res as $k => $v) {
//                if ($d == $v->ins_times) {
                    $result['day'][$k] = date("m-d",strtotime($v->ins_times));//str_replace('-','/',substr($d,2));
                    $result['high'][$k] = $v->high;
                    $result['low'][$k] = $v->low;
//                }
//                continue;
//            }
        }
        return $result;
    }


    /**
     * @param $data
     * @return array
     * 获取日历显示
     */
    public function getCalendarStatistical($data)
    {
        $where[] = ['user_id', '=', $data['user_id']];
//        $where[] = ['case_id', '=', $data['case_id']];
//        $where[] = ['target_id', '=', $data['target_id']];
        // 开始时间
        $weekStart = Carbon::create($data['year'], $data['month'], 1, 0)->startOfMonth();
// 结束时间
        $weekEnd = Carbon::create($data['year'], $data['month'], 1, 0)->endOfMonth();
//        echo "Start of Month: " . $startOfMonth->toDateTimeString() . "\n";
//        echo "End of Month: " . $endOfMonth->toDateTimeString() . "\n"
//        $currentDate = Carbon::now();
//        $weekStart = $currentDate->subMonth();
//        $weekEnd = $currentDate->now();
//        $carbonDate1 = Carbon::createFromFormat('Y-m-d', $weekStart->toDateString());
//        $carbonDate2 = Carbon::createFromFormat('Y-m-d', $weekEnd->toDateString());


        $carbonDate1 = Carbon::createFromFormat('Y-m-d', $weekStart->toDateString());
        $carbonDate2 = Carbon::createFromFormat('Y-m-d', $weekEnd->toDateString());
        // 计算两个日期之间的差异
//        $daysInMonth = $carbonDate1->diffInDays($carbonDate2);

        $daysInMonth = (new \DateTime("{$data['year']}-{$data['month']}-01"))->format('t');
        // 获取当前月份的最后一天
//        $lastDayOfMonth = $currentDate->copy()->endOfMonth();
//        // 获取当月有多少天
//        $daysInMonth = $lastDayOfMonth->day;
//        $weekStart = Carbon::now()->startOfMonth();
//        $weekEnd = Carbon::now()->endOfMonth();
        $res = DB::select('select * from c_target_logs as a right join (select  max(id) as bid from c_target_logs 
              where ins_times BETWEEN :weekStart AND :weekEnd  and user_id = :user_id and case_id = :case_id
              group by ins_times) as b on a.id=b.bid  order by a.ins_times desc',
            ['weekStart' => $weekStart, 'weekEnd' => $weekEnd, 'user_id' => $data['user_id'], 'case_id' => $data['case_id']]);
//        $res = $this::select(DB::raw('max(id) as sort_id'), "c_target_logs.*")
//            ->whereBetween('ins_times', [$weekStart, $weekEnd])
//            ->where($where)
//            ->groupBy("ins_times")
//            ->orderBy("sort_id", "desc")
//            ->get();
        //备忘录
        $memos = (new Memos())->whereBetween('ins_times', [$weekStart, $weekEnd])->distinct("ins_times")->where([['user_id', '=', $data['user_id']], ['case_id', '=', $data['case_id']]])->get();
        //文件夹
        $folder = (new CaseReport())->whereBetween('ins_times', [$weekStart, $weekEnd])->distinct("ins_times")->where([['user_id', '=', $data['user_id']], ['case_id', '=', $data['case_id']]])->get();

        $result = [];
//        $result['list'] = [];
//        $result['target_name'] = (new Target())->where([['id','=',$data['target_id']]])->value("name");
//        if(!empty($res)) {
//            $result['list'] = $res;
//        }
//        $days = date("Y-m", time());
        for ($i = 1; $i <= $daysInMonth; $i++) {
            $d = date("Y-m-d", strtotime($data['year'] . '-' . $data['month'] . '-' . $i)); //$this->getDayBeforeDays($i-1);
//            if ($i < 10) {
//                $ii = '0' . $i;
//            }else{
//                $ii = $i;
//            }
            $result['day'][$i - 1] = str_replace('-', '/', substr($d, 2));
            $result['label'][$i - 1] = 0;
            $result['memos'][$i - 1] = 0;
            $result['folder'][$i - 1] = 0;
            //文件夹
            foreach ($folder as $k => $v) {
                if ($d == $v->ins_times) {
//                    $result['day'][$i - 1] = str_replace('-','/',substr($d,2));
                    $result['folder'][$i - 1] = 1;
                }
                continue;
            }
            //备忘录
            foreach ($memos as $k => $v) {
                if ($d == $v->ins_times) {
//                    $result['day'][$i - 1] = str_replace('-','/',substr($d,2));
                    $result['memos'][$i - 1] = 1;
                }
                continue;
            }
            //标签记录
            foreach ($res as $k => $v) {
                if ($d == $v->ins_times) {
//                    $result['day'][$i - 1] = str_replace('-','/',substr($d,2));
                    $result['label'][$i - 1] = 1;
                }
                continue;
            }
        }
        return $result;
    }








    public function getDayBeforeDays($n) {
        return Carbon::now()->subDays($n)->toDateString();
    }
}
